import { Dept } from '../entitys/Dept';
import { getRepository, In, FindConditions, Like } from 'typeorm';
import { Service } from "typedi";
type DeptKey = keyof Dept
@Service()
export class DeptService{
    async addDept(dept: Dept) {
        if (dept.parentId) {
            const parentDept = await this.getDeptById(dept.parentId)
            if (!parentDept) {
                throw new Error("未找到父部门")
            }
            dept.ancestors = parentDept.ancestors + ","+ parentDept.id
        }
        if(dept.parentId === undefined){
            dept.parentId = 0
        }
        if(dept.sort === undefined){
            dept.sort = 0
        }
        dept.dataStatus = 1
        dept.createTime = new Date()
        dept.updateTime = new Date()
        const deptRepository =  getRepository<Dept>(Dept)
         await deptRepository.save(dept)
        return
    }
    async updateDept(dept:Dept){
        const deptRepository = getRepository(Dept)
        if (dept.parentId) {
            let parentDept = await deptRepository.findOne(dept.parentId)
            if (!parentDept) {
                throw new Error("未找到父部门")
            }
            dept.ancestors = parentDept.ancestors + "," + parentDept.id
        }
        let deptRepo:Dept =  await deptRepository.findOne(dept.id)
        if(!deptRepo){
            throw new Error("未找到对应部门")
        }
        for (let key of Object.keys(deptRepo)) {
            let deptKey = (key as DeptKey)
            if(dept[deptKey]){
                (deptRepo as any)[deptKey] = dept[deptKey]
            }
        }
        deptRepo.updateTime = new Date()
        await deptRepository.save(deptRepo)
    }

    async getDeptTree(name:string,dataStatus:number){
        const deptRepository = getRepository(Dept)
        const where:FindConditions<Dept> = {}
        if (!dataStatus) {
            where.dataStatus = In([0, 1])
        } else {
            where.dataStatus = dataStatus
        }
        if (name) {
            where.name = Like("%"+name+"%")
        }
        const depts = await deptRepository.find({
            where,
            order: {
                sort: "ASC",
                createTime:"ASC"
            }
        })
        let depts2 = this.buildDeptTree(depts)
        if (depts2.length === 0) {
            return depts
        }
        return depts2.concat(depts)  
    }
    async delDept(id:number){
        const deptRepository = getRepository(Dept)
        let dept = await deptRepository.findOne(id)
        if(!dept){
            throw new Error("未找到指定的部门")
        }
        let depts = await deptRepository.find({where: {parentId: dept.id}})
        if (depts) {
            depts.forEach(d => {
                d.dataStatus = -1
            })
            dept.dataStatus = -1
            depts.push(dept)
            await deptRepository.save(depts)
        } else {
            dept.dataStatus = -1
            await deptRepository.save(dept)
        }
        return
    }
    private buildDeptTree(depts:Dept[] ){
        function getRoot(parentId: number) {
            let rootDept = []
            for (let i = 0; i < depts.length; i++) {
                if (depts[i].parentId === parentId) {
                    rootDept.push(depts[i])
                    depts.splice(i, 1)
                    i--
                }
            }
            return rootDept
        }
        function getDeptChildren(rootDepts:Dept[]) {
            rootDepts.forEach((d:any)=>{
                d.children = getRoot(d.id)
                if(d.children.length>0){
                    getDeptChildren(d.children)
                }
            })
        }
        let rootDepts =getRoot(0)
        getDeptChildren(rootDepts)
        return rootDepts
    }
    async getDeptById(id:number): Promise<Dept> {
        const deptRepository = getRepository(Dept)
        const dept = await deptRepository.findOne(id)
        return dept
    }

}
